import React from 'react';
import {Form, Row, Col, Button, DatePicker, message ,Divider,Popconfirm} from 'antd';
import StatisticsBox from '../../components/box/statistics';
import {sessionManager} from '../../utils/sessionStorage';
import AdjustHis from './AdjustHis';
import {injectIntl} from 'react-intl';
import Grid from '../../components/table/grid';
import axios from 'axios';
import moment from 'moment';
import SCModal from '../../components/pickCity/SCModal'

const FormItem = Form.Item;
const createForm = Form.create;

class Settlement extends React.Component {
    constructor(props) {
        super(props);
        this.common = this.props.intl.messages.common;
        this.columnsPop = [
            {
                title: '电站名称',
                dataIndex:'stubGroupName',
                key: 'stubGroupName',
            },
            {
                title: '电量',
                dataIndex: 'electric',
                key: 'electric',
            },
            {
                title: '电费',
                dataIndex: 'electricAmount',
                key: 'electricAmount',
            },
            {
                title: '服务费',
                dataIndex: 'serviceAmount',
                key: 'serviceAmount',
            },
            {
                title: '总费用',
                dataIndex: 'totalAmount',
                key: 'totalAmount',
            }
        ];
        this.columns = [
            {
                title: '结算周期',
                width: '150',
                render: (text) => (
                    text.lastSettlementDate ? `${text.lastSettlementDate}-${text.settlementDate}` : `${text.settlementDate}`
                )
            },
            {
                title: '提交时间',
                dataIndex: 'createTime',
                key: 'createTime',
                width: '150',
            },
            {
                title: '结算电量（度）',
                dataIndex: 'settlementPower',
                key: 'settlementPower',
                width: '150',
            },
            {
                title: '结算电费（元）',
                dataIndex: 'settlementElectric',
                key: 'settlementElectric',
                width: '150',
            },
            {
                title: '结算服务费（元）',
                dataIndex: 'settlementService',
                key: 'settlementService',
                width: '150',
            },
            {
                title: '结算费用（元)',
                dataIndex: 'settlementMoney',
                key: 'settlementMoney',
                width: '150',
            },
            {
                title: '结算状态',
                width: '150',
                render: (text) => (
                    text.status == 0 ? '结算中' : '结算完成'
                )
            },
            {
                title: '调整金额',
                dataIndex: 'adjustmentMoney',
                key: 'adjustmentMoney',
                width: '150',
            },
            {
                title: '实际金额',
                dataIndex: 'money',
                key: 'money',
                width: '150',
            },
            {
                title: this.common.operation,
                key: 'action',
                fixed: 'right',
                width: 180,
                render: (text, record) => (
                    <span>
                        <a onClick={() => this.goLink(text, record, 'BillDetails')}>账单详情</a>
                         <Divider type="vertical"/>
                        <a onClick={() => this.goLink(text, record, 'adjust')}>调整记录</a>
                    </span>

                )
            }
        ];
        this.state = {
            selectTime: moment().subtract(1, 'days').format('YYYY.MM.DD 23:59:59'),
            summary: [],
            visible: false,
            refresh:0,
            popData:[],
            selectedRows:[],
            list:[],
        }
    }

    componentWillMount() {
        this.getTotal()
    }

    handleCancel = () => {
        this.setState({
            visible: false,
        })
    };

    goLink = (text, record, link) => {
        sessionManager.set('BillInfo', text);
        switch (link) {
            case 'BillDetails':
                this.props.history.push({pathname: '/finance/BillDetails'});
                break;
            case 'adjust':
                this.setState({
                    visible: true,
                });
                console.log('adjust');
                break;
            default:
                this.props.history.push('/finance/orderDetails');
        }
    };
    goBill = () => {
        sessionManager.set('BillInfo', this.state.totalData);
        this.props.history.push({pathname: '/finance/BillDetails'});
    };

    submitSettle = () => {
        // let stubGroupId=this.state.list.map(k=>k.id).join(',');
        axios.post('/api/settlement/unSettled/submitSettle', {...{splitTime: this.state.totalData.splitTime}}).then(res => {
            if (res && res.code == 200) {
                if (res.data > 0) {
                  message.success('提交结算操作成功', 1, () => {
                    window.location.reload();
                  });
                } else {
                    message.error('提交结算操作失败')
                }
            }
        })
    };

    submitData=()=>{
        let stubGroupId=this.state.selectedRows.map(k=>k.stubGroupId).join(',');
        axios.post('/api/settlement/unSettled/submitSettle', {...{splitTime: this.state.totalData.splitTime,stubGroupId:stubGroupId}}).then(res => {
            if (res && res.code == 200) {
                if (res.data > 0) {
                  message.success('提交结算操作成功', 1, () => {
                    window.location.reload();
                  });
                } else {
                    message.error('提交结算操作失败')
                }
            }
        })
    }

    transform=(data)=>{
        this.setState({
            popData:data
        })
        return data
    }

    transformData=(data)=>{
        this.setState({
            list:data
        })
        return data
    }

    getTotal = (date = this.state.selectTime) => {
        axios.get('/api/settlement/unsettled/summary', {params: {date: date}}).then(res => {
            if (res && res.code == '200') {
                let flag = false;

                if (Number.parseFloat(res.data.electric) === 0 && Number.parseFloat(res.data.electricAmount)===0 && Number.parseFloat(res.data.serviceAmount)===0 && Number.parseFloat(res.data.totalAmount)===0) {
                    flag = true;
                }
                this.setState({
                    totalData: res.data,
                    summary: [
                        flag?{
                            num: [],
                            actions: () => {
                                return (
                                    <a>&#8212;&#8212;&nbsp;&#8212;&#8212;</a>
                                )
                            }
                        }:{
                            num: res.data.lastSettlementDate ? `${res.data.lastSettlementDate + '-' + res.data.splitTime}` : `${res.data.splitTime}`,
                            desc: '结算周期',
                            style:{width:400}
                        },
                        {
                            num: res.data.electric,
                            desc: '结算电量（度）'
                        }, {
                            num: res.data.electricAmount,
                            desc: '结算电费（元）'
                        },
                        {
                            num: res.data.serviceAmount,
                            desc: '结算服务费（元）'
                        },
                        {
                            num: res.data.totalAmount,
                            desc: '结算费用（元）'
                        },
                        {
                            num: [],
                            actions: () => {
                                return (
                                    flag?<a>&#8212;&#8212;&nbsp;&#8212;&#8212;</a>:<span style={{fontSize: 16}}>
                                    <a onClick={this.goBill}>账单详情</a>
                                    <br/>
                                    <a onClick={this.submitSettle}>提交结算</a>
                                    <br/>
                                    <a onClick={()=>{this.setState({visible4Pop:true})}}>电站结算</a>
                                    </span>
                                )
                            },
                            style:{width:200}
                        }
                    ]
                },()=>{console.log(flag,this.state.totalData)})
            }
        })
    };

    endTimeLess = (rule, value, callback) => {
        if (value.isAfter(moment().format('YYYY.MM.DD'))) {
            callback(`请选择${moment().format('MM月DD日')}之前的时间`);
        } else {
            callback();
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((errors, values) => {
            if (!!errors) {
                console.log('Errors in form!!!');
                return;
            }
            const newVal = {
                ...values,
                orgId: values['orgId'].format('YYYY.MM.DD 23:59:59'),
            };
            console.log(newVal);
            this.getTotal(newVal['orgId']);
            this.setState({
                selectTime:values['orgId'].format('YYYY.MM.DD 23:59:59'),
                refresh:this.state.refresh+1
            })
        });
    }

    render() {
        const {getFieldDecorator} = this.props.form;
        const dateFormat = 'YYYY.MM.DD';
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows
                })
            },
        };
        const totleFeeArr=this.state.selectedRows.map(k=>Number(k.totalAmount));
        const totleFee=totleFeeArr.reduce((preValue=0,curValue,index,array)=>{ return preValue + curValue; },0)
        return (
            <div>
                <form form={this.props.form}>
                    <Row gutter={24} type="flex">
                        <Col xl={5} xxl={3}>
                            <FormItem
                            >
                                {getFieldDecorator('orgId', {
                                    rules: [{validator: this.endTimeLess}],
                                    initialValue: moment().subtract(1, 'days')
                                })(
                                    <DatePicker format={dateFormat} allowClear={false}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={10}>
                            <FormItem>
                                <Button type={'primary'} onClick={this.handleSubmit}>查询</Button>
                                {/* <Button  type={'primary'} style={{marginLeft:8}} onClick={()=>{this.setState({visible4Pop:true})}}>电站分账结算</Button> */}
                            </FormItem>
                        </Col>
                    </Row>
                </form>
                <StatisticsBox params={this.state.summary}/>
                <Grid url="api/settlement/settled/qry" columns={this.columns} refresh={this.state.refresh} transformData={this.transformData}/>
                <AdjustHis visible={this.state.visible} handleCancel={this.handleCancel}/>
                {/* 提交 */}
                <SCModal visible={this.state.visible4Pop} handleCancel={()=>{this.setState({visible4Pop:false})}} title={'提交结算'}>
                    <Grid transformData={this.transform} rowSelection={rowSelection} params={{date:this.state.selectTime}} url="/api/settlement/unsettled/stubGroupSettlement" columns={this.columnsPop} refresh={this.state.refreshPop}/>     
                    {this.state.popData.length>0&&<div style={{textAlign:'center',marginTop:8}}>
                        <Popconfirm title={`结算总费用：${totleFee}元`} okText={'确定'}
                                        onConfirm={this.submitData}
                                        cancelText={'取消'}>
                                <Button  type={'primary'}>提交结算</Button>
                        </Popconfirm>
                    </div>}          
                </SCModal>
            </div>
        )
    }
}

Settlement = createForm()(Settlement);
export default injectIntl(Settlement)
